package com.zte.cl.parser.utils;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import us.codecraft.webmagic.downloader.HttpClientDownloader;

import com.zte.cl.utils.ImageBase64Util;

public class ImageDownloader extends HttpClientDownloader {

	private static final Log log = LogFactory.getLog(ImageDownloader.class);
	
	private HttpResponse _httpResponse;
	
	@Override
	protected String getContent(String charset, HttpResponse httpResponse) throws IOException {
		this._httpResponse=httpResponse;
		byte[] imageByte = EntityUtils.toByteArray(httpResponse.getEntity());
		String iageStr = ImageBase64Util.GetImageStr(imageByte);
		return iageStr;
	}

	public String getImageType() {
		String imageType = "jpg";
		try {
			String contentType =this. _httpResponse.getEntity().getContentType().getValue();
			if (contentType != null) {
				contentType = contentType.toLowerCase();
				if (contentType.equals("image/gif")) {
					imageType = "gif";
				} else if (contentType.equals("image/jpeg")) {
					imageType = "jpg";
				} else if (contentType.equals("image/png")) {
					imageType = "png";
				} else if (contentType.equals("image/tiff")) {
					imageType = "tif";
				}
			}
		} catch (Exception e) {
			log.warn("获取图片类型时发生错误, 使用默认的图片类型jpg!");
			imageType = "jpg";
		}
		return imageType;
	}
}